import {NextRequest, NextResponse} from "next/server";
import {PrismaClient} from "@prisma/client"

const prisma = new PrismaClient()

// 查询投票记录
export async function GET(request: NextRequest) {
    try {
        const {searchParams} = new URL(request.url)
        const userId = searchParams.get("userId") as string
        const topicId = searchParams.get("topicId") as string
        const record = await prisma.record.findFirst({
            where: {
                userId,
                topicId: parseInt(topicId)
            }
        })
        if (!record) {
            return NextResponse.json({
                message: "用户没有投票"
            }, {status: 400})
        }
        return NextResponse.json({
            record
        }, {status: 200})
    }catch (e) {
        return NextResponse.json({
            message: "服务器发生异常"
        }, {status: 500})
    }finally {
        await prisma.$disconnect()
    }
}

// 创建一条投票数据
export async function POST(request: NextRequest) {
    try {
        const {userId, topicId, chooseValue} = await request.json() as {
            userId: string
            topicId: number
            chooseValue: string
        }
        if (!userId || !topicId || !chooseValue) {
            return NextResponse.json({
                message: "参数错误"
            }, {status: 400})
        }
        let recordResult;
        // 开启事务
        await prisma.$transaction(async prisma => {
            // 查找对应的话题信息是否存在
            const topic = await prisma.topic.findFirst({
                where: {
                    id: topicId
                },
                include: {
                    options: true
                }
            })
            if (!topic) {
                return NextResponse.json({
                    message: "话题不存在"
                }, {status: 400})
            }
            // 查找当前用户是否给当前话题投过票
            const record = await prisma.record.findFirst({
                where: {
                    userId,
                    topicId
                }
            })
            if (record) {
                // 根据话题获取到对应的option选项内容
                const option = topic!.options.find(item => item.key === record.chooseValue)
                if (option) {
                    // 更新option选项的value值
                    await prisma.option.update({
                        where: {
                            id: option.id
                        },
                        data: {
                            value: option.value - 1 < 0 ? 0 : option.value - 1
                        }
                    })
                }
                // 删除原来的投票记录
                await prisma.record.delete({
                    where: {
                        id: record.id
                    }
                })
            }
            const chooseOption = topic!.options.find(item => item.key === chooseValue)
            // 更新option选项的value值
            await prisma.option.update({
                where: {
                    id: chooseOption!.id
                },
                data: {
                    value: chooseOption!.value + 1
                }
            })
            // 新增一条投票记录
            recordResult = await prisma.record.create({
                data: {
                    userId,
                    topicId,
                    chooseValue
                },
            })
        })
        return NextResponse.json({
            message: "创建成功",
            record: recordResult
        }, {status: 200})
    } catch (e) {
        return NextResponse.json({
            message: "创建失败"
        }, {status: 500})
    } finally {
        await prisma.$disconnect()
    }
}